package com.nidu.demo.oauth2.ability;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.cola.exception.BizException;
import com.nidu.demo.common.exception.ErrorCodeConstants;
import com.nidu.demo.oauth2.gateway.OAuth2RefreshTokenGateway;
import com.nidu.demo.oauth2.model.OAuth2RefreshToken;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class OAuth2RefreshTokenDomainService {

    private final OAuth2RefreshTokenGateway gateway;

    public OAuth2RefreshToken validateRefreshToken(String refreshToken, Long clientId) {
        OAuth2RefreshToken oAuth2RefreshToken = gateway.getByRefreshToken(refreshToken);
        if (oAuth2RefreshToken == null){
            throw new BizException(ErrorCodeConstants.REFRESH_TOKEN_INVALID.getCode(), ErrorCodeConstants.REFRESH_TOKEN_INVALID.getMessage());
        }
        oAuth2RefreshToken.isExpired();

        // 校验 Client 匹配
        if (ObjectUtil.notEqual(clientId, oAuth2RefreshToken.getClientId())) {
            throw new BizException(ErrorCodeConstants.OAUTH2_REFRESH_TOKEN_CLIENT_FAIL.getCode(), ErrorCodeConstants.OAUTH2_REFRESH_TOKEN_CLIENT_FAIL.getMessage());
        }
        return oAuth2RefreshToken;
    }
}
